package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.util.UUID;

/**
 * 阿里云OSS工具类
 *
 * @Author: Zhy
 * @Date: 2025-01-19 20:59
 * @Version: 1.0
 */
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

	private String endpoint;
	private String accessKeyId;
	private String accessKeySecret;
	private String bucketName;
	private String domain;

	/**
	 * 文件上传方法，将字节数组上传到阿里云OSS，并返回文件的访问路径
	 *
	 * @return: String 文件的访问路径
	 * @param: bytes 要上传的文件字节数组
	 * @param: objectName 上传到OSS的文件名
	 */
	public String upload(byte[] bytes, String filename) {

		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

		// 获取文件名后缀（即文件类型），如：.jpg
		String suffix = filename.substring(filename.lastIndexOf("."));

		// 生成随机文件名，并拼接文件类型，.jpg ---> 0256e2648807434fa54dd66597c69e37.jpg
		filename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;

		try {
			// 创建PutObject请求。
			ossClient.putObject(bucketName, filename, new ByteArrayInputStream(bytes));
		} catch (OSSException oe) {
			System.out.println(
				"Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
			System.out.println("Error Message:" + oe.getErrorMessage());
			System.out.println("Error Code:" + oe.getErrorCode());
			System.out.println("Request ID:" + oe.getRequestId());
			System.out.println("Host ID:" + oe.getHostId());
		} catch (ClientException ce) {
			System.out.println(
				"Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS,  such as not being able to access the network.");
			System.out.println("Error Message:" + ce.getMessage());
		} finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}

		// 文件访问路径规则 https://hzhm-mlgb2.oss-cn-beijing.aliyuncs.com/14eefbb123014c8f83703c96ffe8ed2f.jpg
		StringBuilder stringBuilder = new StringBuilder("https://");
		stringBuilder.append(bucketName).append(".").append(domain).append("/").append(filename);

		log.info("文件上传到:{}", stringBuilder.toString());

		return stringBuilder.toString();
	}
}
